#!/usr/bin/python
# -*- coding: utf-8 -*-
import logging
import omencore as tools
import multiprocessing.queues as mqueue
import omencore as omendaemon
import omencore as omenlog
import time

def test_creation_log_file():
    tools.FileTools.delete_file('file/log/log_test.log', False)
    logger = logging.getLogger('test_application')
    fh = logging.FileHandler('file/log/log_test.log')
    fh.setLevel(logging.INFO)
    fh.setFormatter(logging.Formatter("%(asctime)-25s|%(name)-30s|%(levelname)-8s|%(message)s"))
    logger.addHandler(fh)
    logger.info("this is a test message")
    ee = logging.getLogger("test_application.other")
    ee.error("this is a error test message")
    del logger
    
    try:
        content = tools.FileTools.read_text('file/log/log_test.log')
        lines = content.splitlines()
        assert lines[1].split('|')[2].strip() == 'ERROR'
        assert lines[1].split('|')[1].strip() == 'test_application.other'
        assert lines[1].split('|')[3].strip() == 'this is a error test message'
        assert True
    except:
        assert False

def function_for_logging(a_log_queue):
    mylogger = logging.getLogger('test_queue_logger')
    fh = logging.FileHandler('file/log/log_queue_test.log')
    fh.setLevel(logging.INFO)
    fh.setFormatter(logging.Formatter("%(asctime)-25s|%(name)-30s|%(levelname)-8s|%(message)s"))
    mylogger.addHandler(fh)
    mylogger2 = omenlog.TestLogger(a_log_queue)
    mylogger2.info('start')
    
    omenlog.QueuedLogManager.log_from_queue_for_ever(mylogger, a_log_queue)
    
def function_for_product(log_queue):
#     local_logger = logging.getLogger('test_queue_logger.local')
#     handler = omenlog.QueueHandler(log_queue)
# #     handler.setLevel(logging.INFO)
# #     handler.setFormatter(logging.Formatter("%(asctime)-25s|%(name)-30s|%(levelname)-8s|%(message)s"))
#     local_logger.addHandler(handler)
#     local_logger.info('test')
#     local_logger.info('test')
#     local_logger.info('test')
#     local_logger.info('test')
    mylogger = omenlog.TestLogger(log_queue)
    mylogger.info('test')
    mylogger.info('test')
    mylogger.info('test')
    mylogger.info('test')
        
def test_queue_log_file():
    tools.FileTools.delete_file('file/log/log_queue_test.log', False)
    log_queue = mqueue.Queue()
    
    
    log_proc = omendaemon.DaemonFactory.get_daemon("Log process", 
            function_for_logging, (log_queue,), omendaemon.DaemonType.PROCESS)
    log_proc.start()
    
    lp = []
    for i in range(5):
        log_prod = omendaemon.DaemonFactory.get_daemon("productor%s" % (str(i)), 
                function_for_product, (log_queue, ), omendaemon.DaemonType.PROCESS)
        log_prod.start()
        lp.append(log_prod)
    
    time.sleep(5)
    
    log_proc.terminate()
    log_proc.join()
    
    for pp in lp:
        pp.terminate()
        pp.join()
